package com.ch1;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

@Sharable
public class EchoClientHandler extends ChannelInboundHandlerAdapter{
	static final String ECHO_REQ = "Hello world$$";
	
	private static int COUNTER=10; 
	
   
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		  System.out.println(">>>>> Client is channelRead0");
			 System.out.println(">>>>>"+msg );
			
			 ReferenceCountUtil.release(msg);
	}
	
	
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       System.out.println(">>>>> Client is active");
    	
    	for (int i = 0; i < COUNTER; i++) {
       	 ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
       	 System.out.println(">>>>>Send="+ECHO_REQ);
		}

    	 
    
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    	// TODO Auto-generated method stub
    
        ctx.flush();
        ctx.close();
        System.out.println(">>>>> Client is channelReadComplete");
    }
    
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    		throws Exception {
       cause.printStackTrace();
       ctx.close();
       
    
    }
 
}
